package ods_field

import (
	"fmt"
	"server/global"
	"server/model/common/request"
)

type OdsDbFieldService struct {
}

func (odsDbFieldService *OdsDbFieldService) CreateOdsDbField(odsDbField *OdsDbField) (err error) {
	err = global.SysDB.Create(odsDbField).Error
	return err
}

func (odsDbFieldService *OdsDbFieldService) DeleteOdsDbField(odsDbField OdsDbField) (err error) {
	err = global.SysDB.Delete(&odsDbField).Error
	return err
}

func (odsDbFieldService *OdsDbFieldService) DeleteOdsDbFieldByIds(ids request.IdsReq) (err error) {
	err = global.SysDB.Delete(&[]OdsDbField{}, "id in ?", ids.Ids).Error
	return err
}

func (odsDbFieldService *OdsDbFieldService) UpdateOdsDbField(odsDbField OdsDbField) (err error) {
	err = global.SysDB.Save(&odsDbField).Error
	return err
}

func (odsDbFieldService *OdsDbFieldService) GetOdsDbFieldById(id uint) (odsDbField OdsDbField, err error) {
	err = global.SysDB.Where("id = ?", id).First(&odsDbField).Error
	return
}

func (odsDbFieldService *OdsDbFieldService) GetOdsDbFieldInfoList(info OdsDbFieldSearch) (list []OdsDbField, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&OdsDbField{})
	var odsDbFields []OdsDbField
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&odsDbFields).Error
	return odsDbFields, total, err
}

func (odsDbFieldService *OdsDbFieldService) GetAllOdsDbFields() (odsDbField []OdsDbField, err error) {
	err = global.SysDB.Find(&odsDbField).Error
	return odsDbField, err
}

func (odsDbFieldService *OdsDbFieldService) GetOdsDbFieldByCol(colName string, colVal string, colOrder string) (odsDbField []OdsDbField, err error) {
	tbData := global.SysDB.Model(&OdsDbField{})
	var odsDbFields []OdsDbField
	if colName != "" && colVal != "nil" {
		strFindFld := fmt.Sprintf("%s = ?", colName)
		tbData = tbData.Where(strFindFld, colVal)
	}
	if colOrder != "" {
		err = tbData.Order(colOrder).Find(&odsDbFields).Error
	} else {
		err = tbData.Find(&odsDbFields).Error
	}

	return odsDbFields, err
}
